﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace YunZiChanApi.Yunbo
{
    public class BaseMiddleware : BaseController
    {
        private readonly RequestDelegate _next;

        public BaseMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 执行自定义逻辑

          
            var isAuthorization = context.Request.Headers.TryGetValue("Authorization", out var authorizationHeader);
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status200OK;
            //验证请求头是否存在token


            if (!isAuthorization)
            {
                var data = new { Success = false, Message = "缺少Authorization参数" };
                var jsonData = JsonConvert.SerializeObject(data);
                await context.Response.WriteAsync(jsonData);
                return;
            }
            if (!authorizationHeader.ToString().Contains("bearer "))
            {
                var data = new { Success = false, Message = "参数中缺少bearer 字符" };
                var jsonData = JsonConvert.SerializeObject(data);
                await context.Response.WriteAsync(jsonData);
                return;
            }




            // 调用下一个中间件
            await _next(context);
        }
    }
}
